package demo.IOStream;

import java.io.*;
import java.util.Arrays;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/13-08-13-11:47
 * @Description：demo.IOStream
 */
public class outputFile {
    public static void main(String[] args) {
        File file = new File("hello.txt");
        String[] str = {"hello world!","你好，世界"};
        //writeString(file,str);
        String s = "hello";
        int count = NumOfstr(file,s);
        System.out.println(s + "在文件中出现的次数为：" + count);
    }

    private static int NumOfstr(File file, String s) {
        FileReader reader = null;
        int index = 0,count = 0;
        try {
            reader = new FileReader(file);
            int len = -1;
            char[] b = new char[1024];
            String str = "";
            while((len = reader.read()) != -1){
                str = str + (char)len;
            }
            System.out.println(str);

            while((index = str.indexOf(s,index)) != -1){
                count++;
                index = index + s.length();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }

    public static void writeString(File file,String[] str){
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            for (String s : str) {
                writer.write(s);
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
